package cn.xunjie.ymcc.service.impl;

import cn.xunjie.ymcc.doc.CourseDoc;
import cn.xunjie.ymcc.dto.CourserSearchDto;
import cn.xunjie.ymcc.mapper.HighlightResultMapper;
import cn.xunjie.ymcc.repository.CourseEsRepository;
import cn.xunjie.ymcc.result.AggrPageList;
import cn.xunjie.ymcc.result.AggrsBucket;
import cn.xunjie.ymcc.result.PageList;
import cn.xunjie.ymcc.service.ICourseEsService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;

import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ICourseEsServiceImpl implements ICourseEsService {
    @Autowired
    private CourseEsRepository courseEsRepository;
    @Autowired
    private ElasticsearchRestTemplate template;
    @Autowired
    private HighlightResultMapper highlightResultMapper;
    @Override
    public void saveCourse(CourseDoc doc) {
        courseEsRepository.save(doc);
    }

    @Override
    public PageList<CourseDoc> search(CourserSearchDto dto) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //排序条件
        if(StringUtils.hasLength(dto.getSortField())){
            String sortField = null;
            switch (dto.getSortField().toLowerCase()){
                case "xl": sortField="saleCount";break;
                case "xp": sortField="onlineTime";break;
                case "pl": sortField="commentCount";break;
                case "jg": sortField="price";break;
                case "rq": sortField="viewCount";break;
                default: break;
            }
            if(sortField != null){
                if(StringUtils.hasLength(dto.getSortType())){
                    SortOrder sortOrder = dto.getSortType().equalsIgnoreCase("ASC") ? SortOrder.ASC : SortOrder.DESC;
                    builder.withSort(new FieldSortBuilder((sortField)).order(sortOrder));

                }

            }
        }
        builder.withPageable(PageRequest.of(dto.getPage()-1, dto.getRows()));
        //高亮
        HighlightBuilder.Field highlightField = new HighlightBuilder.Field("name")
                .preTags("<span style='color:red'>")
                .postTags("</span>");
        builder.withHighlightFields(highlightField);
        //聚合查询
        builder.addAggregation(AggregationBuilders.terms("aggGradeName").field("gradeName"));
        builder.addAggregation(AggregationBuilders.terms("aggChargeName").field("chargeName"));

        //封装查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.hasLength(dto.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("name",dto.getKeyword()));
        }
        if(dto.getCourseTypeId() != null){
            boolQuery.filter(QueryBuilders.termQuery("courseTypeId",dto.getCourseTypeId()));
        }
        if(StringUtils.hasLength(dto.getGradeName())){
            boolQuery.filter(QueryBuilders.termQuery("gradeName",dto.getGradeName()));
        }
        if(StringUtils.hasLength(dto.getChargeName())){
            boolQuery.filter(QueryBuilders.termQuery("chargeName",dto.getChargeName()));
        }
        if(dto.getPriceMin() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMin()));
        }
        if(dto.getPriceMax() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }
        builder.withQuery(boolQuery);
        NativeSearchQuery build = builder.build();
        AggregatedPage<CourseDoc> page = template.queryForPage(build,CourseDoc.class, highlightResultMapper);
               /* courseEsRepository.search(build);*/
        Map<String, Aggregation> map = page.getAggregations().asMap();
        ParsedStringTerms aggGradeName = (ParsedStringTerms) map.get("aggGradeName");
        ParsedStringTerms aggsChargeName = (ParsedStringTerms)map.get("aggChargeName");

        List<AggrsBucket> aggrsBuckets = new ArrayList<>();
        aggGradeName.getBuckets().forEach(bucket -> {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            AggrsBucket aggrsBucket = new AggrsBucket(key, docCount);
            aggrsBuckets.add(aggrsBucket);

        });
        List<AggrsBucket> aggrsBuckets1 = new ArrayList<>();
        aggsChargeName.getBuckets().forEach(bucket -> {
            String key = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            AggrsBucket aggrsBucket = new AggrsBucket(key, docCount);
            aggrsBuckets1.add(aggrsBucket);
        });
        Map<String, List<AggrsBucket>> Aggrmap = new HashMap<>();
        Aggrmap.put("aggGradeName",aggrsBuckets);
        Aggrmap.put("aggChargeName",aggrsBuckets1);

        return new AggrPageList<>(page.getTotalElements(),page.getContent(),Aggrmap);



    }


}
